home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / epsilon / unrepr.py < prev    next >
Text File  |  2009-03-13  |  1KB  |  55 lines

  1. import compiler
  2.  
  3. def unrepr(s):
  4.     """
  5.     Convert a string produced by python's repr() into the
  6.     corresponding data structure, without calling eval().
  7.     """
  8.     return Builder().build(getObj(s))
  9.  
  10. def getObj(s):
  11.     s="a="+s
  12.     return compiler.parse(s).getChildren()[1].getChildren()[0].getChildren()[1]
  13.  
  14. class UnknownType(Exception):
  15.     pass
  16.  
  17. class Builder:
  18.  
  19.     def build(self, o):
  20.         m = getattr(self, 'build_'+o.__class__.__name__, None)
  21.         if m is None:
  22.             raise UnknownType(o.__class__.__name__)
  23.         return m(o)
  24.  
  25.     def build_List(self, o):
  26.         return map(self.build, o.getChildren())
  27.  
  28.     def build_Const(self, o):
  29.         return o.value
  30.  
  31.     def build_Dict(self, o):
  32.         d = {}
  33.         i = iter(map(self.build, o.getChildren()))
  34.         for el in i:
  35.             d[el] = i.next()
  36.         return d
  37.  
  38.     def build_Tuple(self, o):
  39.         return tuple(self.build_List(o))
  40.  
  41.     def build_Name(self, o):
  42.         if o.name == 'None':
  43.             return None
  44.         raise UnknownType('Name')
  45.  
  46.     def build_Add(self, o):
  47.         real, imag = map(self.build_Const, o.getChildren())
  48.         try:
  49.             real = float(real)
  50.         except TypeError:
  51.             raise UnknownType('Add')
  52.         if not isinstance(imag, complex) or imag.real != 0.0:
  53.             raise UnknownType('Add')
  54.         return real+imag
  55.